package com.atguigu.day26.problem03;

import org.junit.Test;

import java.sql.*;

/*
获取自增的主键
 */
public class KeyTest {
    @Test
    public void test01() throws SQLException {

        //1.注册驱动
        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "1234");
        //3.准备sql
        String sql = "insert into t_account values(null,?,?)";
        //4.创建命令发送器
        PreparedStatement pst = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
        //5.填充数据
        pst.setObject(1,"刘亦菲");
        pst.setObject(2,5000);
        //6.执行命令
        pst.executeUpdate();
        //7.获取自增的主键
        ResultSet rs = pst.getGeneratedKeys();
        while (rs.next()){
            //8.展示主键值
            int aid = rs.getInt(1);
            System.out.println("aid = " + aid);
        }
        //9.关闭资源
        rs.close();
        pst.close();
        connection.close();


    }
}
